import logging

from odoo import api, fields, models, _, tools
from odoo.exceptions import ValidationError

_logger = logging.getLogger(__name__)


class MrpRoutingWorkcenter(models.Model):
    _inherit = 'mrp.routing.workcenter'
    _order = 'bom_id, step,sequence, id'

    param_line_ids = fields.One2many(
        'mrp.routing.workcenter.param.line', 'workcenter_id', 'Work Center Params', copy=True
    )
    step = fields.Integer(string="Procedures", default=0)
    # department_id = fields.Many2one('hr.department', related='workcenter_id.department_id')
    thai_name = fields.Char(string="Thai Name", related="workcenter_id.thai_name")
    eng_name = fields.Char(string="English Name", related="workcenter_id.eng_name")
    work_station_id = fields.Many2one('work.station', related="workcenter_id.work_station_id", string='Work Station')
    is_drill_operation = fields.Boolean(string='Drill operation?', default=False)
    # 钻孔表
    drill_operation_ids = fields.Many2many(
        comodel_name='mrp.routing.workcenter.drill',
        relation='routing_workcenter_drill_rel',
        column1='workcenter_id',
        column2='drill_operation_id',
        string='Drill Operation'
    )
    # 背钻作业
    is_back_drill_operation = fields.Boolean(string='Back Drill operation?', default=False)
    back_drill_operation_ids = fields.Many2many(
        comodel_name='mrp.routing.workcenter.back.drill',
        relation='routing_workcenter_back_drill_rel',
        column1='workcenter_id',
        column2='back_drill_operation_id',
        string='Back Drill Operation'
    )
    # 控深钻程式
    drill_depth_program = fields.Char(string='控深钻程式')
    drill_unit = fields.Char(string='drill Unit')
    # 钻带钻孔总孔数
    drill_hole_total = fields.Integer(string='钻孔总孔数')

    drill_image = fields.Image(string='Drill')
    time_cycle_manual = fields.Float('Manual Duration', default=0.1)

    @api.constrains('step')
    @api.onchange('step')
    def _onchange_step(self):
        for rec in self:
            s = '%02d' % rec.step
            if rec.workcenter_id:
                rec.name = s + '.' + rec.workcenter_id.display_name.strip()

    @api.onchange('workcenter_id')
    def _onchange_workcenter_id(self):
        if self.step == 0:
            bom = self.bom_id
            if bom:
                _logger.info(bom.id)
                _logger.info(bom.operation_ids.ids)
                bom_olines = len(bom.operation_ids.ids)
                self.step = bom_olines + 1
        s = '%02d' % self.step
        if self.workcenter_id:
            self.name = s + '.' + self.workcenter_id.display_name.strip()
        icount = len(self.param_line_ids)
        # if icount == 0:
        lines = []
        bom_lines = self.env['mrp.workcenter.param.line'].search([('workcenter_id', 'in', self.workcenter_id.ids)])
        if bom_lines:
            self.param_line_ids = [(5, 0)]
            index = 1
            for item in bom_lines:
                lines.append((0, 0, {
                    'attribute_id': item.attribute_id.id,
                    'value_id': item.value_id.id,
                    'sequence': index
                }))
                index += 1
            self.param_line_ids = lines

    # def write(self, vals):
    #     for rec in self:
    #         if self.env['mrp.production'].search_count([('bom_id', '=', rec.bom_id.id), ('state', 'not in', ('done', 'cancel'))]) > 0:
    #             raise ValidationError(_('There are manufacturing orders in production that cannot be modified!'))
    #
    #     return super().write(vals)

    def unlink(self):
        for rec in self:
            if self.env['mrp.production'].search_count(
                    [('bom_id', '=', rec.bom_id.id), ('state', 'not in', ('done', 'cancel'))]) > 0:
                raise ValidationError(_('There are manufacturing orders in production that cannot be deleted!'))

        return super().unlink()

    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            bom_id = vals.get('bom_id')
            if not bom_id:
                continue
            if self.env['mrp.production'].search_count(
                    [('bom_id', '=', bom_id), ('state', 'not in', ('done', 'cancel'))]) > 0:
                raise ValidationError(
                    _('There are manufacturing orders in production that are not allowed to be created!'))

        return super().create(vals_list)


class MrpRoutingWorkcenterParam(models.Model):
    """Attributes available on product.template with their selected values in a m2m.
    Used as a configuration model to generate the appropriate product.template.attribute.value"""
    _name = "mrp.routing.workcenter.param.line"
    _rec_name = 'attribute_id'
    _rec_names_search = ['attribute_id']
    _description = 'Work Center Param Line'
    _order = 'attribute_id, id'

    active = fields.Boolean(default=True)
    workcenter_id = fields.Many2one('mrp.routing.workcenter', string="Route Work Center", ondelete='cascade',
                                    required=True, index=True)
    attribute_id = fields.Many2one('product.attribute', string="Attribute", domain="[('limit_type', '=', 'route')]",
                                   ondelete='restrict', required=True, index=True)
    thai_name = fields.Char(string="Thai Name", related='attribute_id.thai_name')
    eng_name = fields.Char(string="English Name", related='attribute_id.eng_name')

    value_id = fields.Many2one('product.attribute.value', string="Values",
                               domain="[('attribute_id', '=', attribute_id)]")

    z_thai_name = fields.Char(string="Value T Name", related='value_id.thai_name')
    z_eng_name = fields.Char(string="Value E Name", related='value_id.eng_name')
    sequence = fields.Integer(string="Sequence", default=1)

    # @api.constrains('z_thai_name', 'z_eng_name', 'thai_name', 'eng_name')
    # def onchange_z_name(self):
    #     if self.z_thai_name:
    #         self.value_id.thai_name = self.z_thai_name
    #     if self.z_eng_name:
    #         self.value_id.eng_name = self.z_eng_name
    #     if self.thai_name:
    #         self.attribute_id.thai_name = self.thai_name
    #     if self.eng_name:
    #         self.attribute_id.eng_name = self.eng_name

    @api.model_create_multi
    def create(self, vals_list):
        self.attribute_id = self.attribute_id.filtered(lambda pav: pav.limit_type == 'route')
        return super(MrpRoutingWorkcenterParam, self).create(vals_list)

    # @api.constrains('attribute_id', 'value_id')
    # @api.onchange('attribute_id', 'value_id')
    # def _onchange_attribute_id(self):
    #     for record in self:
    #         if record.attribute_id:
    #             record.thai_name = record.attribute_id.thai_name
    #             record.eng_name = record.attribute_id.eng_name
    #         if record.value_id:
    #             record.z_thai_name = record.value_id.thai_name
    #             record.z_eng_name = record.value_id.eng_name

    # @api.onchange('attribute_id')
    # def _onchange_attribute_id(self):
    #     self.value_ids = self.value_ids.filtered(lambda pav: pav.attribute_id == self.attribute_id)

    # @api.constrains('active', 'value_ids', 'attribute_id')
    # def _check_valid_values(self):
    #     for ptal in self:
    #         if ptal.active and not ptal.value_ids:
    #             raise ValidationError(
    #                 _("The attribute %s must have at least one value for the workcenter %s.") %
    #                 (ptal.attribute_id.display_name, ptal.workcenter_id.display_name)
    #             )
    #         for pav in ptal.value_ids:
    #             if pav.attribute_id != ptal.attribute_id:
    #                 raise ValidationError(
    #                     _("On the workcenter %s you cannot associate the value %s with the attribute %s because they do not match.") %
    #                     (ptal.workcenter_id.display_name, pav.display_name, ptal.attribute_id.display_name)
    #                 )
    #     return True


# 钻孔作业
class MrpRoutingWorkcenterDrill(models.Model):
    _name = 'mrp.routing.workcenter.drill'
    _description = 'Drill Work Center'
    _rec_name = 'name'

    # 刀号
    cutter_number = fields.Char('Cutter Number')
    # 连接层
    connection_layer = fields.Char('Connection Layer')
    # 钻带名称
    name = fields.Char('Drill Name')
    # 成孔(mm)
    finished_drill_solt_size = fields.Char('Finished Drill Slot Size')
    # Slot长(mm)
    drill_solt_size = fields.Char('Drill Slot Size')
    # 正公差(mm)
    drill_tolerance = fields.Char('Drill Tolerance')
    # 负公差(mm)
    drill_negative_tolerance = fields.Char('Drill Negative Tolerance')
    # 钻径(mm)
    drill_diameter = fields.Char('Drill Diameter')
    # Slot加工长度(mm)
    drill_length = fields.Char('Drill Length')
    # PTH
    n_pth = fields.Char('Number of PTH')
    # 加工方式
    drill_method = fields.Char('Drill Method')
    # PCS孔数
    pcs_hole_number = fields.Char('PCS Hole Number')
    # SET孔数
    set_hole_number = fields.Char('SET Hole Number')
    # PNL孔数
    pnl_hole_number = fields.Char('PNL Hole Number')
    # 塞孔方式
    slot_type = fields.Char('Slot Type')
    # 控深
    depth_control = fields.Char('Depth Control')
    # 二钻
    second_drill = fields.Char('Second Drill')
    remark = fields.Char('Remark')
    active = fields.Boolean(default=True)


class MrpRoutingWorkcenterBackDrill(models.Model):
    _name = 'mrp.routing.workcenter.back.drill'
    _description = 'Back Drill Work Center'

    holeSeq = fields.Char(string="孔序号", required=True)
    thruHoleBit = fields.Char(string="通孔钻咀")
    # 深钻成孔
    deepDrillDia = fields.Char(string="[深钻成孔]直径")
    deepDrillTolPlus = fields.Char(string="公差+")
    deepDrillTolMinus = fields.Char(string="公差-")
    # 深钻钻咀
    deepBitDia = fields.Char(string="[深钻钻咀]直径")
    deepBitAngle = fields.Char(string="尖角(°)")
    # 客规 Stub
    stubCustMin = fields.Char(string="最小")
    stubCustMax = fields.Char(string="最大")
    stubInt = fields.Char(string="内控Stub")
    # PTH 残柱
    pthStumpCust = fields.Char(string="客规")
    pthStumpInt = fields.Char(string="内控")
    # 调机含铝片
    setupAlDepth = fields.Char(string="深度")
    setupAlTol = fields.Char(string="公差±")

    distDrill = fields.Char(string="分步钻")
    mustThruLayers = fields.Char(string="必钻穿层")
    noThruLayers = fields.Char(string="不钻穿层")
    isPth = fields.Char(string="PTH")
    # 深钻孔数
    deepHoleCntPcs = fields.Char(string="PCS")
    deepHoleCntPnl = fields.Char(string="PNL")
    layer = fields.Char(string="钻带名称")
    remark = fields.Char(string="备注")
    active = fields.Boolean(default=True)
